local function get_client_ip()
    local headers = ngx.req.get_headers()
    local clientIP = headers["x-forwarded-for"]
    if clientIP == nil or string.len(clientIP) == 0 or clientIP == "unknown" then
        clientIP = headers["Proxy-Client-IP"]
    end
    if clientIP == nil or string.len(clientIP) == 0 or clientIP == "unknown" then
        clientIP = headers["WL-Proxy-Client-IP"]
    end
    if clientIP == nil or string.len(clientIP) == 0 or clientIP == "unknown" then
        clientIP = ngx.var.remote_addr
    end
    -- 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
    if clientIP ~= nil and string.len(clientIP) > 15 then
        local pos = string.find(clientIP, ",", 1)
        clientIP = string.sub(clientIP, 1, pos - 1)
    end
    return clientIP;
end

local function check_cn(ip)
    local geo = require 'resty.maxminddb'
    if not geo.initted() then
        geo.init("/etc/nginx/mmdb/Country.mmdb")
    end
    local res, err = geo.lookup(ip)
    if not res then
        ngx.log(ngx.ERR, ' failed to lookup by ip , reason :', err)
    else
        for k, v in pairs(res) do
            if (k == "country") then
                for key, item in pairs(v) do
                    if (key == "iso_code") then
                        if item == "CN" then
                            ngx.log(ngx.INFO, ' this counrty: ', item)
                            return 1;
                        else
                            ngx.log(ngx.ERR, ' this counrty: ', item)
                            return 0;
                        end
                    end
                end
            end
        end
    end
end



-- 获取nginx 本地缓存
local cache_ngx = ngx.shared.dis_cache;
-- 获取 请求IP
local clientIP = get_client_ip();


--根据IP 获取本地黑名单缓存数据
local banIpCache = cache_ngx:get('ban_ip_' .. clientIP);
if banIpCache == 1 then
    ngx.log(ngx.ERR, "cache_black_ip:", clientIP)
    ngx.exit(403)
else
    -- 判断是否是国外IP, 直接设为黑名单,并且返回403
    local flag = check_cn(clientIP);
    if flag == 0 then
        -- 本地缓存黑名单 时间1小时
        ngx.log(ngx.ERR, "set_local_black_ip:", clientIP)
        cache_ngx:set('ban_ip_' .. clientIP, 1, 60 * 60);
        ngx.exit(403)
    end
end



